$OpenBSD: patch-util_c,v 1.1 2013/11/24 02:27:08 jeremy Exp $

Backport r43776 and r43782 from Ruby SVN to fix CVE-2013-4164.

--- util.c.orig	Sun Nov 21 23:21:34 2010
+++ util.c	Thu Nov 21 22:40:16 2013
@@ -892,6 +892,11 @@ extern void *MALLOC(size_t);
 #else
 #define MALLOC malloc
 #endif
+#ifdef FREE
+extern void FREE(void*);
+#else
+#define FREE free
+#endif
 
 #ifndef Omit_Private_Memory
 #ifndef PRIVATE_MEM
@@ -1176,7 +1181,7 @@ Balloc(int k)
 #endif
 
     ACQUIRE_DTOA_LOCK(0);
-    if ((rv = freelist[k]) != 0) {
+    if (k <= Kmax && (rv = freelist[k]) != 0) {
         freelist[k] = rv->next;
     }
     else {
@@ -1186,7 +1191,7 @@ Balloc(int k)
 #else
         len = (sizeof(Bigint) + (x-1)*sizeof(ULong) + sizeof(double) - 1)
                 /sizeof(double);
-        if (pmem_next - private_mem + len <= PRIVATE_mem) {
+        if (k <= Kmax && pmem_next - private_mem + len <= PRIVATE_mem) {
             rv = (Bigint*)pmem_next;
             pmem_next += len;
         }
@@ -1205,6 +1210,10 @@ static void
 Bfree(Bigint *v)
 {
     if (v) {
+        if (v->k > Kmax) {
+            FREE(v);
+            return;
+        }
         ACQUIRE_DTOA_LOCK(0);
         v->next = freelist[v->k];
         freelist[v->k] = v;
@@ -2200,6 +2209,7 @@ break2:
         for (; c >= '0' && c <= '9'; c = *++s) {
 have_dig:
             nz++;
+            if (nf > DBL_DIG * 4) continue;
             if (c -= '0') {
                 nf += nz;
                 for (i = 1; i < nz; i++)
